angular.module('mamApp').controller('programmeController', ['$scope', '$state', '$uibModal', 'FileUploader', 'api', 'ProgramsManager', 'AlbumManager', '$filter', 'ChannelManager', 'BaseValidations','ImsErr',
    function ($scope, $state, $uibModal, FileUploader, api, ProgramsManager, AlbumManager, $filter, ChannelManager, BaseValidations,ImsErr) {

        $scope.image = false;
        $scope.disabled = false;
        $scope.sureDissbled = false;
        $scope.image_a = false;
        $scope.BaseValidations = BaseValidations;
        var albumId = $state.params.albumId;
        $scope.programId = $state.params.programId;
        $scope.album = {commonTagsSelected: [], specialTagsSelected: []};

        $scope.formData = {};


        $scope.list = [1];
        setTimeout(function () {
            $scope.list = [];
        },200)

        ChannelManager.commTagsList().then(function (result) {
            $scope.commonTags = [];
            $scope.commonDimensionsName = {};
            result.data.list.forEach(function (item) {
                $scope.commonDimensionsName[item.dimensionId] = item.dimensionsName;
                if (item.hasOwnProperty("list")) {
                    item.list.forEach(function (tag) {
                        $scope.commonTags.push({
                            commtagId: tag.commtagId,
                            dimensionId: item.dimensionId,
                            commtagName: tag.commtagName
                        })
                    })
                }
            })


        })


        $scope.specialTagsList = function (channelId) {
            $scope.specialTags = [];
            $scope.specialDimensionsName = {};

            ChannelManager.specialTagsList(channelId).then(function (result) {
                result.data.list.forEach(function (item) {
                    $scope.specialDimensionsName[item.dimensionId] = item.dimensionsName;

                    if (item.hasOwnProperty("list")) {
                        item.list.forEach(function (tag) {
                            $scope.specialTags.push({
                                specialId: tag.specialId,
                                dimensionId: tag.dimensionId,
                                specialName: tag.specialName
                            })
                        })
                    }

                })

            })
        }

        /**
         * 专辑改变请求详细信息
         * @param album
         */

        $scope.albumChange = function (album) {
            AlbumManager.albumDetail(album.albumId).then(function (result) {
                $scope.albumData = result.data.cpAlbumVO;
                $scope.formData.programCover = $scope.albumData.albumCover;
                $scope.formData.keyword = $scope.albumData.keyword.join(",");
                $scope.formData.anchorName = $scope.albumData.anchorName;
                $scope.formData.originalName = $scope.albumData.originalName;
                $scope.formData.summary = $scope.albumData.summary;
                $scope.specialTagsList($scope.albumData.channelId)

                var tmpComm = [];
                var tmpSpe = [];

                $scope.albumData.commList.forEach(function (tag) {
                    tmpComm.push({
                        commtagId: tag.commtagId,
                        dimensionId: tag.dimensionId,
                        commtagName: tag.commtagName
                    })
                })
                $scope.albumData.specialList.forEach(function (tag) {
                    tmpSpe.push({
                        specialId: tag.specialId,
                        dimensionId: tag.dimensionId,
                        specialName: tag.specialName
                    })
                })
                $scope.album.commonTagsSelected = tmpComm;
                $scope.album.specialTagsSelected = tmpSpe;
            })
        }


        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.commGroupFn = function (item) {
            return $scope.commonDimensionsName[item.dimensionId]
        };
        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */
        $scope.noAlbum=false;
        $scope.specialGroupFn = function (item) {
            return $scope.specialDimensionsName[item.dimensionId]
        };

        AlbumManager.albumList([1, 100]).then(function (result) {
            if(result.data.total==0){
                $scope.noAlbum=true;
            }else {
                $scope.noAlbum=false;
            }

            $scope.albumList = result.data.pageList;
            if (albumId) {
                console.log($filter('filter')($scope.albumList, {albumId: albumId}))
                $scope.album.albumSelected = $filter('filter')($scope.albumList, {albumId: albumId})[0];
                $scope.albumChange($scope.album.albumSelected)

            }


        });
        $scope.myImage = '';
        $scope.myCroppedImage = '';

        var handleFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];

            $scope.uploadCover(file);

        };

        setTimeout(function () {
            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        }, 1000)

        $scope.uploadCover = function (image) {
            if(image.type.indexOf("image")==-1){
                $scope.$apply($scope.errorImg='仅支持PNG/JPG/JPEG格式');
                return false;
            }else {
                $scope.$apply($scope.errorImg='');
            }
            var modalInstance = $uibModal.open({
                animation: true,
                backdrop:false,
                templateUrl: 'uploadCover.html',
                controller: 'coverManageController',
                resolve: {
                    params: function () {
                        return {image: image,coverType:"program"};

                    }
                }
            });
            modalInstance.result.then(function (result) {
                $("#fileInput").prop("value","");

                if (result.url) {
                    $scope.formData.programCover = result.url;

                }

            })
        }


        $scope.search = {
            status: $state.params.status
        };

        $scope.tabClick = function (index) {
            if ($scope.programId) {
                return false;
            }
            $scope.search.status = index;
            $scope.search.pageNo=1;
            $state.go($state.current.name, $scope.search);
        };

        $scope.uploaderAudio = new FileUploader({
            alias: "uploadFile",
            queueLimit: $scope.search.status == "single" || !$scope.search.status ? 1 : 20,//文件个数
            // removeAfterUpload: true,//上传后删除文件 */
            filters: [{
                name: 'uploadFile',//后台接收字段
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    if (!/\.(mp3|MP3|AAC|aac)$/.test(item.name)) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者AAC格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false;
                    }
                    else if (item.size > 150 * 1024 * 1024 || item.size < 0.5 * 1024 * 1024) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者AAC格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false;
                    } else {
                        $scope.image_a = false;
                        return true;
                    }
                }
            }],
            onSuccessItem: function (fileItem, response, headers) {
                if (response.c == "s") {
                    delete  response.c;
                    fileItem.webUrl = response.fileVO.webUrl;
                    $scope.list.push({file: response.fileVO, audio: response.audioInfoVO});
                } else {
                    fileItem.isSuccess = 'uploadFail';

                }
            },
            url: api + "/cp/programs/audio",
            headers: {'X-Auth-Token': $scope.userInfo.token}
        });

        $scope.uploadAllAudio = function () {
            $scope.uploaderAudio.uploadAll();
        };


        $scope.submitSingle = function () {
            $scope.sureDissbled = true;
            $scope.formData.albumId = $scope.album.albumSelected.albumId;
            var commTag = [];
            var specialTag = [];
            $scope.album.commonTagsSelected.forEach(function (item) {
                commTag.push(item.commtagId)
            })
            $scope.album.specialTagsSelected.forEach(function (item) {
                specialTag.push(item.specialId)
            })
            $scope.formData.commTag = commTag.join(",");
            $scope.formData.keyword = $scope.formData.keyword.split(",");

            $scope.formData.specialTag = specialTag.join(",");
            $scope.formData.file = $scope.list[0].file;
            $scope.formData.audio = $scope.list[0].audio;

            ProgramsManager.programSingleAdd($scope.formData.albumId, $scope.formData).then(function (result) {
                $scope.sureDissbled = false;
                if (result.data.c == "s") {
                    $state.go("main.album.info", {albumId: $scope.formData.albumId}, {reload: true})
                }else {
                    $scope.formData.keyword = $scope.formData.keyword.join(",")
                    ImsErr.open({message:result.data.i}).then(function (a) {
                    })
                }
            })
        };

        $scope.cancel = function () {
            $state.go("main.album.info", {albumId: albumId});
        };


        $scope.removeFile = function ($index, item) {
            $scope.list.forEach(function (file) {
                if (file.file.webUrl == item.webUrl) {
                    $scope.list.splice($scope.list.indexOf(file), 1);
                }
            })


        }
        $scope.submitBatch = function () {
            $scope.disabled = true;
            $scope.formData.albumId = $scope.album.albumSelected.albumId;

            ProgramsManager.programBatchAdd($scope.formData.albumId, $scope.list).then(function (result) {
                $scope.disabled = false;
                if (result.data.c == "s") {
                    $state.go("main.album.info", {albumId: $scope.formData.albumId}, {reload: true})
                }
            })
        }


    }]);

